#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <time.h>

#include "ff_wrap.h"
#include "avi.h"

#define TEST_AVI_FILE "rec_test.avi"

int main(int argc, char *argv[])
{
	int ret = 0;
	st_ff_context ff_ctx;
	struct avi_media_param mparam;
	memset(&mparam,0,sizeof(mparam));

	printf(">>> start avi test...\n");
	/** video param */
	mparam.video_cbr = 1;
	mparam.video_bitrate = 512*1024;
	mparam.video_framerate = 10;
	mparam.video_gop = 10;
	mparam.video_codec = 1;
	mparam.video_width = 704;
	mparam.video_height = 576;
	mparam.pic_level = 1;
	/** audio param */
	mparam.audio_sample_fmt = 16;
	mparam.audio_sample_rate = 44100;/// FIXME: 441000
	mparam.audio_channels = 2;
	mparam.audio_bitrate = 64000;
	mparam.audio_codec = 1;

	printf("[test avi_fix_handle]...\n");
	ret = avi_fix_handle("2202032_fix.avi");
	printf("avi_fix_handle ret = %d\n",ret);

	AVI_HANDLE pavi = avi_init_handle(TEST_AVI_FILE,&mparam,AVI_STREAM_VAMIX);
	if(pavi==NULL)
	{
		printf("avi_init_handle fail!\n");
		exit(EXIT_FAILURE);
	}

	unsigned char frame[8192]={0};
	int frames = 1024, size = 0;
	int type = 0, i = 0;

	srand(time(NULL));

	ret = ff_init_demuxer("sample.avi",&ff_ctx);
	printf(">>>[test ff_init_demuxer]ret = %d\n",ret);
	AVPacket pkt;
	av_init_packet(&pkt);
	pkt.data = NULL;
	pkt.size = 0;

	while(frames--)
	{
#if 0
		size = rand()%8192;
		if(size < 340) size = 340;
		for(i=0;i<size;i++)
			frame[i] = rand()%255;
		ret = avi_write_packet(pavi,type,frame,size);
#else
		if(av_read_frame(ff_ctx.fmt_ctx,&pkt)<0)
		{
			printf("av_read_frame error!\n");
			continue;
		}
		ret = avi_write_packet(pavi,pkt.stream_index,pkt.data,pkt.size);
		av_free_packet(&pkt);
#endif
		if(ret < 0)
			printf("!!!! avi_write_packet error!\n");
		//type = !type;// video and audio interleaved
		usleep(100000);
	}

	ret = ff_exit_demuxer(&ff_ctx);
	printf(">>>[test ff_exit_demuxer]ret = %d\n",ret);

	avi_exit_handle(pavi);
	printf("<<< end avi test.\n");

	return ret;
}

